package com.application.sistercityapplication.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.PowerManager;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.application.sistercityapplication.dto.MagazineDto;
import com.application.sistercityapplication.main.BooksAdapter;
import com.application.sistercityapplication.model.Magazine;
import com.todddavies.components.progressbar.ProgressWheel;

public class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    private ProgressWheel progressWheel;
    private MagazineDto magazineDto;
    private String pdfPath,tumnailPath;
    private ImageView imageView;
    private BaseAdapter baseAdapter;

    public DownloadTask(Context context,ProgressWheel progressWheel,MagazineDto magazineDto,BaseAdapter baseAdapter) {
        this.context = context;
        this.progressWheel = progressWheel;
        this.magazineDto = magazineDto;
        this.baseAdapter = baseAdapter;
    }
    public DownloadTask(Context context,ProgressWheel progressWheel,MagazineDto magazineDto,ImageView imageView,BaseAdapter baseAdapter) {
        this.context = context;
        this.progressWheel = progressWheel;
        this.magazineDto = magazineDto;
        this.imageView = imageView;
        this.baseAdapter = baseAdapter;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
        	String id = "";
        	String cat = "";
        	if(magazineDto.getMagId()!=null){
        		id = magazineDto.getMagId();
        		cat = "mag";
        	}else if(magazineDto.getKmsId()!=null){
        		id = magazineDto.getKmsId();
        		cat = "kms";
        	}else if(magazineDto.getMouId()!=null){
        		id = magazineDto.getMouId();
        		cat = "mou";
        	}
        	File Directory = new File(
					Environment.getExternalStorageDirectory()
							+ "/SisterCity/download/"+cat+"_"
							+ id);
			if (!Directory.exists()) {
				Directory.mkdirs();
			}
			 URL urlPdf = new URL(magazineDto.getPath());
	            connection = (HttpURLConnection) urlPdf.openConnection();
	            connection.connect();

	            // expect HTTP 200 OK, so we don't mistakenly save error report
	            // instead of the file
//	            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
//	                return "Server returned HTTP " + connection.getResponseCode()
//	                        + " " + connection.getResponseMessage();
//	            }

	            // this will be useful to display download percentage
	            // might be -1: server did not report the length
	            int fileLength2 = connection.getContentLength();

	            // download the file
	            input = connection.getInputStream();
	            final String pdfName = magazineDto.getPath().substring(
	            		magazineDto.getPath().lastIndexOf('/') + 1,
	            		magazineDto.getPath().length());
	            File pdf = new File(Directory, pdfName);
	            output = new FileOutputStream(pdf);
	            pdfPath = pdf.getAbsolutePath();
	            byte data2[] = new byte[4096];
	            long total2 = 0;
	            int count2;
	            while ((count2 = input.read(data2)) != -1) {
	                // allow canceling with back button
	                if (isCancelled()) {
	                    input.close();
	                    return null;
	                }
	                total2 += count2;
	                // publishing the progress....
	                if (fileLength2 > 0) // only if total length is known
	                {
	                publishProgress((int) (total2 * 100 / fileLength2));
	                output.write(data2, 0, count2);
	                }else{
	                output.write(data2, 0, count2);	
	                }
	            }
			

            if (output != null)
                output.close();
            if (input != null)
                input.close();
            if (connection != null)
                connection.disconnect();
            URL urlTumb = new URL(magazineDto.getTumbnail());
            connection = (HttpURLConnection) urlTumb.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            final String tumbName = magazineDto.getTumbnail().substring(
            		magazineDto.getTumbnail().lastIndexOf('/') + 1,
            		magazineDto.getTumbnail().length());
            File imageThumb = new File(Directory, tumbName);
            tumnailPath = imageThumb.getAbsolutePath();
            output = new FileOutputStream(imageThumb);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                 publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
           
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user 
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
             getClass().getName());
        mWakeLock.acquire();
        progressWheel.spin();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        //progressWheel.set
      //  mProgressDialog.setMax(100);
        //mProgressDialog.setProgress(progress[0]);
        progressWheel.setText(progress[0]+" % ");
        
        if(progress[0]>= 100){
        	progressWheel.stopSpinning();
        	progressWheel.setVisibility(View.GONE);
        	
        	
        	Magazine magazine = new Magazine();
        	if(magazineDto.getMagId()!=null){
	        	if(magazine.checkDuplicateData(magazineDto.getMagId())){
		        	magazine.id = magazine.getPk();
		        	magazine.countryId = magazineDto.getCountryId();
		        	magazine.cat = magazineDto.getCat();
		        	magazine.created_at = magazineDto.getCreated_at();
		        	magazine.magId = magazineDto.getMagId();
		        	magazine.path = pdfPath;
		        	magazine.tumbnail = tumnailPath;
		        	magazine.title = magazineDto.getTitle();
		        	magazine.updeted_at = magazineDto.getUpdeted_at();
		        	magazine.catId = "1";
		        	magazine.save();
	        	}
        	}
        	if(magazineDto.getKmsId()!=null){
        		if(magazine.checkDuplicateData(magazineDto.getKmsId(),"kmsId")){
	        		magazine.id = magazine.getPk();
		        	magazine.countryId = magazineDto.getCountryId();
		        	magazine.cat = magazineDto.getCat();
		        	magazine.created_at = magazineDto.getCreated_at();
		        	magazine.kmsId = magazineDto.getKmsId();
		        	magazine.path = pdfPath;
		        	magazine.tumbnail = tumnailPath;
		        	magazine.title = magazineDto.getTitle();
		        	magazine.updeted_at = magazineDto.getUpdeted_at();
		        	magazine.save();
        		}
        	}
        	if(magazineDto.getMouId()!=null){
        		if(magazine.checkDuplicateData(magazineDto.getMouId(),"mouId")){
	        		magazine.id = magazine.getPk();
		        	magazine.countryId = magazineDto.getCountryId();
		        	magazine.cat = magazineDto.getCat();
		        	magazine.created_at = magazineDto.getCreated_at();
		        	magazine.mouId = magazineDto.getMouId();
		        	magazine.path = pdfPath;
		        	magazine.tumbnail = tumnailPath;
		        	magazine.title = magazineDto.getTitle();
		        	magazine.updeted_at = magazineDto.getUpdeted_at();
		        	magazine.save();
        		}
        	}
        	if(imageView!=null){
	        	imageView.getDrawable().mutate().setAlpha(255);
	        	imageView.invalidate();
	        	}
	        	baseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        //mProgressDialog.dismiss();
      
       
    }
}


